#include <REGX52.H>
#include "Delay_Utils.h"

static unsigned char Single_Keyboard_Down_Key;

/**
 * 获得独立按键, 按下时会一直停留在此函数, 松开才返回按键的值
 * 1.逐个按键扫描
 * 2.P1口整体赋值, 整体读取判断
 * @return 按下: 1~4, 未按下: 0
 */
unsigned char Single_Keyboard_Down_Delay(bit isTx1C) {
    if (isTx1C) {
        //如果K1按下    延时跳过抖动   [如果还是按下状态, 就一直循环, 直到松手]  [松手后再延时跳过抖动]
        if(P3_4 == 0) { DelayShake(); while(P3_4 == 0);                       DelayShake();         return 1; }
        if(P3_5 == 0) { DelayShake(); while(P3_5 == 0); DelayShake(); return 2; }
        if(P3_6 == 0) { DelayShake(); while(P3_6 == 0); DelayShake(); return 3; }
        if(P3_7 == 0) { DelayShake(); while(P3_7 == 0); DelayShake(); return 4; }
        return 0;
    }
    //视频
    if(P3_1 == 0) { DelayShake(); while(P3_1 == 0); DelayShake(); return 1; }
    if(P3_0 == 0) { DelayShake(); while(P3_0 == 0); DelayShake(); return 2; }
    if(P3_2 == 0) { DelayShake(); while(P3_2 == 0); DelayShake(); return 3; }
    if(P3_3 == 0) { DelayShake(); while(P3_3 == 0); DelayShake(); return 4; }
    return 0;
}

/**
 * 获得 Timer 调用后的独立按键
 * 一般在main 的while(1) 中调用
 * @return 按下后抬起: 1~4,  未按下/一直按住: 0
 */
unsigned char Single_Keyboard_Down_Timer_Get() {
    static unsigned char temp;
    temp = Single_Keyboard_Down_Key;
    //按键值要清0后再返回, 因为Timer 15ms扫描1次的话, 还是上次的值
    Single_Keyboard_Down_Key = 0;
    return temp;
}

/**
 * 获得独立按键, 松开才有按键的值
 * 1.在定时器中断函数内 调用此函数, 每15ms调用1次
 */
void Single_Keyboard_Down_Timer(bit isTx1C) {
    //上一个按键
    static unsigned char preKey, nowKey;
    preKey = nowKey;
    if (isTx1C) {
        if(P3_4 == 0) nowKey = 1;
        else if(P3_5 == 0) nowKey = 2;
        else if(P3_6 == 0) nowKey = 3;
        else if(P3_7 == 0) nowKey = 4;
        else nowKey = 0;
    } else {
        //视频
        if(P3_1 == 0) nowKey = 1;
        else if(P3_0 == 0) nowKey = 2;
        else if(P3_2 == 0) nowKey = 3;
        else if(P3_3 == 0) nowKey = 4;
        else nowKey = 0;
    }
    //如果上一次按下 & 这次松手
    if (preKey && !nowKey) Single_Keyboard_Down_Key = preKey;
}